package com.foxit.adapp;
// Filename: Getad.java
// Compile: javac Getad.java
import java.io.*;
import java.net.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;
import com.couchbase.client.CouchbaseClient;


public class Getad extends HttpServlet {
   LookupService lookup=null;
   private String REDIRECT="";
   private String COUCHURI="";
   private int MAXADS=0;

   public void init(ServletConfig config) throws ServletException{
      super.init(config);
      ServletContext context = getServletContext();
      REDIRECT =  context.getInitParameter("REDIRECT");
      COUCHURI =  context.getInitParameter("COUCH_URI");
      String GEOCITY = context.getInitParameter("GEOCITY");
      MAXADS = Integer.valueOf(context.getInitParameter("MAXADS"));
      try {
         File file = new File(GEOCITY);
         lookup = new LookupService(file,LookupService.GEOIP_MEMORY_CACHE);
      } catch(IOException e) {
      }
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
      response.setContentType("application/json;charset=UTF-8");
      request.setCharacterEncoding("UTF-8");
      PrintWriter out = response.getWriter();   
// get input json
      String udid = request.getParameter("udid");
      InData u =  (InData) JSON.parseObject(udid, InData.class);
// connect couchbase , check nation
      CouchbaseClient client=null;
      try {
         List<URI> hosts = Arrays.asList(new URI(COUCHURI));
         client = new CouchbaseClient(hosts, "default", "");
         String ipAddress="";
         if(u.getNation()==null || u.getNation().length()==0) {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null) {
               ipAddress = request.getHeader("X_FORWARDED_FOR");
               if (ipAddress == null){
                  ipAddress = request.getRemoteAddr();
               }
            }
            u.setNation(getNation(ipAddress));
         }
      } catch(Exception ex) {
         JsonOut jo= new JsonOut(-1, ex.getMessage(),u.getMember(),null,null,null);
         String json = JSON.toJSONString(jo);
         out.println(json);
         return;
      }
      String servset=(String) client.get("SERVER_"+u.getServer());
      ServerSetting ss= new ServerSetting(servset);
      String membsetting = (String) client.get("MEMBER");

      MemberSet mset= new MemberSet(u.getMember(),membsetting);
     // process AD
      int uno = udid_no(u.getUdid());
      ArrayList<ShowMode> adset = ss.getSetting();
      int adno = adset.size();
      int g=0, type=0, browser=0;

      List<JsonInfo> jsonlist = new ArrayList<JsonInfo>();
      AdidInfo adid = new AdidInfo("",u.getLang(),u.getServer(),u.getUdid(),REDIRECT,u.getNation(),"",0,0,0);
      //List<JsonAD> jal;

      for(int i=0;i < adno;i++)  {
         List<JsonAD> jal= new ArrayList<JsonAD>();
         g = uno % adset.get(i).getGroupno();     
         adid.setGroup(adset.get(i).getGroupno());
         adid.setGroupno(g);
         adid.setShowMode(adset.get(i).getName());
         type = adset.get(i).getAGroup().get(g).getType(); 
         browser = adset.get(i).getBrowser(); 
         //String adrule="";
         //List<JsonAD> jal= new ArrayList<JsonAD>();
         JsonInfo ji = new JsonInfo(adset.get(i).getName(),jal,0);
         switch(type) {
            case 1: // 輪播廣告 
               jal = Add_AD(adset.get(i).getAGroup().get(g).getAD(),adid,browser,client,u.getLang(),4);
               ji.setType(4);
               break;
            case 2: 
               if(u.getClickad()!=null && u.getClickad().length() != 0) {
                  String[] cad = u.getClickad().split(",");
                  String rl="";
                  for(int k=0;k < cad.length;k++) {
                     adid.setIdInfo((String)client.get("AD_"+cad[k]),u.getLang()); 
                     if(rl != "") rl += ",";
                     rl += (String) client.get("REL_"+adid.getRelated());
                  }
                  // 相關廣告 
                  jal = Add_AD(rl,adid,browser,client,u.getLang(),3);
                  ji.setType(3);
               } else {
                  switch(mset.getAdtype()) {
                     case 1: // 相關廣告
                        jal = Add_AD(u.getClickad(),adid,browser,client,u.getLang(),3);
                        ji.setType(3);
                        break;
                     case 2: // 重要訊息廣告
                        String impmsg=(String) client.get("IMPMSG");
                        jal = Add_AD(impmsg,adid,browser,client,u.getLang(),0);
                        ji.setType(0);
                        break;
                     case 3: // NO AD
                        break;
                     case 0:
                     default:
                        if(u.getAdflag()==1) { 
                           // 動作廣告
                           String actad=adset.get(i).getAGroup().get(g).getAD();
                           String actset = (String) client.get("ACT_"+actad);
                           ActionAD aa = new ActionAD(u.getUdid(),actset,u.getTrace_info());;
                           //String groupinfo=(String)client.get(u.getUdid()); 
                           String groupinfo="3,rs1;3,mo1;3,t1;2,t2;2,t4;2,t5;1,t6;1,t7"; 
                           if(u.getTrace_info()==null && groupinfo==null) {
                              // default AD
                              String defstr=(String) client.get("DEFAULTAD");
                              jal = Add_AD(defstr,adid,browser,client,u.getLang(),0);
                              ji.setType(0);
                           } else {
                              if(browser==1) {
                                 String[] a=aa.getAD1(groupinfo);
                                 if(a != null) {
                                    adid.setInfoData(a[0],1,(String)client.get("AD_"+a[0]),u.getLang(),a[1]);
                                    jal.add(new JsonAD(adid.getImgPath(),adid.getRedPath()));
                                    ji.setType(1);
                                 }
                              } else {
                                 ArrayList<String[]> a=aa.getADS1(groupinfo,MAXADS);
                                 if(a != null) {
                                    for(int j=0;j<a.size();j++) {
                                       adid.setInfoData(a.get(j)[0],1,(String)client.get("AD_"+a.get(j)[0]),u.getLang(),a.get(j)[1]);
                                       jal.add(new JsonAD(adid.getImgPath(),adid.getRedPath()));
                                    }
                                    ji.setType(1);
                                 }
                              }
                           }
                        } else {
                           // 分組廣告
                           //String groupinfo=(String)client.get(u.getUdid());
                           String gset = (String) client.get("GROUP");
                           String groupinfo="3,rs1;3,mo1;3,t1;2,t2;2,t4;2,t5;1,t6;1,t7"; 
                           if(gset==null || groupinfo==null) {
                              String defstr=(String) client.get("DEFAULTAD");
                              jal = Add_AD(defstr,adid,browser,client,u.getLang(),0);
                              ji.setType(0);
                           } else {
                              GroupAD gpa = new GroupAD(u.getUdid(),gset);;
                              if(browser==1) {
                                 String[] a=gpa.getAD1(groupinfo);
                                 if(a != null) {
                                    adid.setInfoData(a[0],1,(String)client.get("AD_"+a[0]),u.getLang(),a[1]);
                                    jal.add(new JsonAD(adid.getImgPath(),adid.getRedPath()));
                                    ji.setType(2);
                                 }
                              } else {
                                 ArrayList<String[]> a=gpa.getADS(groupinfo,MAXADS);
                                 if(a != null) {
                                    for(int j=0;j<a.size();j++) {
                                       adid.setInfoData(a.get(j)[0],1,(String)client.get("AD_"+a.get(j)[0]),u.getLang(),a.get(j)[1]);
                                       jal.add(new JsonAD(adid.getImgPath(),adid.getRedPath()));
                                    }
                                    ji.setType(2);
                                 }
                              }
                           }
                        } // if(u.getAdflag()==1)
                  } //switch(mset.getAdtype())
               //break;
            } // switch(type)
         } 
         ji.setJsonAD(jal);
         jsonlist.add(ji);
      } // for(int i=0;i < adno;i++)
      client.shutdown();
      JsonPolicy policy=new JsonPolicy(mset.getShowtime(),mset.getShowmode());
      JsonOut jo= new JsonOut(0,"success",u.getMember(),jsonlist,policy,null);

      String json = JSON.toJSONString(jo);
      out.println(json);
  }

  public String getNation(String ip) {
      if(ip==null || ip.length()==0) return "";
      if(lookup==null) return "";
      Location locationServices = lookup.getLocation(ip);
      if(locationServices==null ) {
         return "CN";
      }
      return locationServices.countryCode;
  }

   public int udid_no(String udid) {
        String[] ids = udid.split("-");
        int no = 0;
        int x;
        try {
           for(String id:ids) {
               x = Integer.parseInt(id,16);
               no += x;
           }
       } catch (Exception e) {
           return 0;
       }
        return no;
   }

   public List<JsonAD> Add_AD(String info,AdidInfo adid,int browser,CouchbaseClient client,String lang,int type) {
       List<JsonAD> jal= new ArrayList<JsonAD>();
       GenAD ro= new GenAD( info );
       if(browser==1) {
          String rad=ro.getAD();
          adid.setInfoData(rad,type,(String)client.get("AD_"+rad),lang);
          jal.add(new JsonAD(adid.getImgPath(),adid.getRedPath()));
       } else {
          String[] rads=ro.getADS(MAXADS);
          for(int j=0;j < rads.length;j++) {
             adid.setInfoData(rads[j],type,(String)client.get("AD_"+rads[j]),lang);
             jal.add(new JsonAD(adid.getImgPath(),adid.getRedPath()));
          } 
      }
      return jal;
   }
}

